package com.ruoyi.common.utils;

import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class CalculatorUtils {
    /**
     * 使用exp4j库计算表达式
     * @param expression 数学表达式，如 "(x-32768)/10"
     * @param x 变量x的值
     * @return 计算结果
     * @throws IllegalArgumentException 如果表达式有误
     */
    public static String calculateWithExp4j(String expression, double x) {
        Expression exp = new ExpressionBuilder(expression)
                .variable("x")
                .build()
                .setVariable("x", x);

        double result = exp.evaluate();

        // 使用BigDecimal进行四舍五入
        BigDecimal bd = new BigDecimal(result);
        bd = bd.setScale(3, RoundingMode.HALF_UP);

        return bd.toString();
    }

    public static void main(String[] args) {
        String expression = "(x-32768)/10";
        String result2;
        if (expression.contains("x")) {
            result2 = CalculatorUtils.calculateWithExp4j("(x-32768)/10", 32778);
            System.out.println("exp4j 结果: " + result2);
        }

        result2 = CalculatorUtils.calculateWithExp4j("x*1", 3.5);
        System.out.println("exp4j 结果: " + result2);
        result2 = CalculatorUtils.calculateWithExp4j("x*0.1", 68.358);
        System.out.println("exp4j 结果: " + result2);
        result2 = CalculatorUtils.calculateWithExp4j("0.1", 68.358);
        System.out.println("exp4j 结果: " + result2);
        result2 = CalculatorUtils.calculateWithExp4j("68.358*0.1-2", 68.358);
        System.out.println("exp4j 结果: " + result2);
    }
}
